package com.common.aspectj;

import com.common.anntation.DataScope;
import com.model.base.BaseEntity;
import com.common.emums.DataScopeType;
import com.common.utils.ServletUtils;
import com.common.utils.SpringUtils;
import com.common.utils.StringUtils;
import com.core.springSecurity.common.SecurityUtils;
import com.core.springSecurity.model.LoginUserDetails;
import com.core.springSecurity.service.TokenService;
import com.model.pojo.sys.SysRole;
import com.model.pojo.sys.SysUser;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 数据过滤处理
 *
 * @author
 */
@Aspect
@Component
public class DataScopeAspect
{


    /**
     * 数据权限过滤关键字
     */
    public static final String DATA_SCOPE = "dataScope";

    /** 配置织入点*/
    @Pointcut("@annotation(com.common.anntation.DataScope)")
    public void dataScopePointCut()
    {
    }

    @Before("dataScopePointCut()")
    public void doBefore(JoinPoint point) throws Throwable
    {
        handleDataScope(point);
    }

    protected void handleDataScope(final JoinPoint joinPoint)
    {
        // 获得注解
        DataScope controllerDataScope = getAnnotationLog(joinPoint);
        if (controllerDataScope == null)
        {
            return;
        }
        // 获取当前的用户
        LoginUserDetails loginUserDetails = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        if (StringUtils.isNotNull(loginUserDetails))
        {
            SysUser currentUser = loginUserDetails.getUser();
            // 如果是超级管理员，则不过滤数据
            if (StringUtils.isNotNull(currentUser) && !SecurityUtils.isAdmin(currentUser.getSysUserId()))
            {
                dataScopeFilter(joinPoint, loginUserDetails);
            }
        }
    }

    /**
     * 数据范围过滤
     *
     * @param joinPoint 切点
     * @param loginUserDetails 用户
     */
    public static void dataScopeFilter(JoinPoint joinPoint,  LoginUserDetails loginUserDetails)
    {
        StringBuilder sqlString = new StringBuilder();

        for (SysRole role : loginUserDetails.getRoles())
        {
            Byte dataScope = role.getDataScope();
            if (DataScopeType.DATA_SCOPE_ALL.getCode().equals(dataScope))
            {
                sqlString = new StringBuilder();
                break;
            }
            else if (DataScopeType.DATA_SCOPE_CUSTOM.getCode().equals(dataScope))
            {
                sqlString.append(StringUtils.format(
                        " OR d.sys_dept_id IN ( SELECT sys_dept_id FROM sys_role_dept WHERE sys_role_id = {} ) ", role.getSysRoleId()));
            }
            else if (DataScopeType.DATA_SCOPE_DEPT.getCode().equals(dataScope))
            {
                sqlString.append(StringUtils.format(" OR d.sys_dept_id = {} ", loginUserDetails.getUser().getSysDeptId()));
            }
            else if (DataScopeType.DATA_SCOPE_DEPT_AND_CHILD.getCode().equals(dataScope))
            {
                sqlString.append(StringUtils.format(
                        " OR d.sys_dept_id IN ( SELECT sys_dept_id FROM sys_dept WHERE sys_dept_id = {} or  find_in_set( {} , ancestors ) )",
                        loginUserDetails.getUser().getSysDeptId(),loginUserDetails.getUser().getSysDeptId()));
            }
            else if (DataScopeType.DATA_SCOPE_SELF.getCode().equals(dataScope))
            {
                    sqlString.append(StringUtils.format(" OR d.sys_user_id = {} ", loginUserDetails.getUser().getSysUserId()));
            }
        }

        if (StringUtils.isNotBlank(sqlString.toString()))
        {
            Object params = joinPoint.getArgs()[0];
            if (StringUtils.isNotNull(params) && params instanceof BaseEntity)
            {
                BaseEntity baseEntity = (BaseEntity) params;
                baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")");
            }
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private DataScope getAnnotationLog(JoinPoint joinPoint)
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
            return method.getAnnotation(DataScope.class);
        }
        return null;
    }

    /*
        mybatis 部分改动参考
        表明要命名一个别名d where条件加入params.dataScope
        select *  from tableName d where ${params.dataScope}
    */
}
